package cn.stronglink.assetmanage.business.inspection.view.repair;

/**
 * Created by zhengjinglan on 2018/6/21.
 */

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.stronglink.assetmanage.MyApplication;
import cn.stronglink.assetmanage.R;
import cn.stronglink.assetmanage.business.check.view.CheckFragment;
import cn.stronglink.assetmanage.business.inspection.adapter.RepairAdapter;
import cn.stronglink.assetmanage.business.inspection.model.RepairModel;
import cn.stronglink.assetmanage.business.inspection.presenter.RepairPresenter;
import cn.stronglink.assetmanage.dao.DaoManager;
import cn.stronglink.assetmanage.dao.SyncTypesDao;
import cn.stronglink.assetmanage.entity.RepailDetail;
import cn.stronglink.assetmanage.entity.Repair;
import cn.stronglink.assetmanage.entity.Result;
import cn.stronglink.assetmanage.entity.SyncTypes;
import cn.stronglink.assetmanage.index.view.onRecyclerListener;
import cn.stronglink.assetmanage.utils.Constants;
import cn.stronglink.assetmanage.utils.ToastUtil;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 维修登记列表
 */
public class RepairFragment extends Fragment implements RepairModel.onRepairListener {
    private RepairAdapter listAdapter;
    private RepairModel repairModel;
    private RepairView repairView;
    private RepairPresenter repairPresenter;
    //维修单列表
    private RecyclerView rv_repair_list;
    private LinearLayoutManager layoutManager;
    private Map<String, Repair> repairMap = new HashMap<>();    //获取数据库的维修单列表

    private TextView  txt_title_left , txt_title_right,txt_main_title;     //标题栏左边和右边
    private SwipeRefreshLayout refresh_list_repair;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_repair, container, false);
        try {
            initViewAndData(view);
        }catch (Exception e){
            e.printStackTrace();
        }

        return view;
    }

    private void initViewAndData(View view) {
        txt_title_left = this.getActivity().findViewById(R.id.txt_left_title);
        txt_title_left.setVisibility(View.GONE);
        txt_title_right = this.getActivity().findViewById(R.id.txt_right_title);
        txt_title_right.setVisibility(View.GONE);
        txt_main_title = this.getActivity().findViewById(R.id.txt_main_title);
        txt_main_title.setText("巡检维修");

        listAdapter = new RepairAdapter(this.getActivity());
        rv_repair_list = view.findViewById(R.id.rv_repair_list);
        layoutManager = new LinearLayoutManager(this.getActivity(), LinearLayout.VERTICAL, false);
        rv_repair_list.setLayoutManager(layoutManager);
        rv_repair_list.setAdapter(listAdapter);
        listAdapter.setOnItemClickListener(new onRecyclerListener() {
            @Override
            public void onItemClicked(View v, int postion) {
                if(postion>=0) {
                    repairPresenter.showOrderByPosition(postion);
                }
            }
        });

        repairModel = new RepairModel();
        repairModel.setRepairListener(this);
        repairView = new RepairView(this, view, listAdapter);
        repairPresenter = new RepairPresenter(repairModel, repairView);

        refresh_list_repair = view.findViewById(R.id.refresh_list_repair);
        refresh_list_repair.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //判断是离线还是在线
                SyncTypes syncTypes = DaoManager.getDaoSession(getActivity()).getSyncTypesDao().
                        queryBuilder().where(SyncTypesDao.Properties.IsSelected.eq(true)).unique();
                int tp = 0;
                if (syncTypes != null) {
                    tp = syncTypes.getSyscTs();
                }
                switch (tp) {
                    case 1:

                        repairModel.getRepairData();
                        break;
                    case 2:
                        //从数据库拿数据
                        repairModel.getDataByRepairIdDistince();
                        ToastUtil.toastShort("本地维修单获取成功");
                        refreshView();
                        refresh_list_repair.setRefreshing(false);
                        break;
                }

            }
        });
        repairPresenter.initRepairListData();

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onFailer(Call call, final IOException ex) {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                refresh_list_repair.setRefreshing(false);
                ToastUtil.toastShort(ex.getMessage());
            }
        });

    }

    @Override
    public void onResponse(Call call, final Response response) {

        try {

            if (response.isSuccessful()) {
                if (response.code() == 200) {
                    String json = response.body().string();
                    if (json != null && !"".equals(json)) {
                        Result<List<Repair>> repairResult = null;
                        Gson gson = new Gson();
                        repairResult = gson.fromJson(json, new TypeToken<Result<List<Repair>>>() {
                        }.getType());
                        if (repairResult != null && repairResult.getHttpCode() == HttpURLConnection.HTTP_OK) {
                            if (repairResult.getData() != null) {
                                List<Repair> repairList = repairResult.getData();
                                // 验收单列表
                                if (repairList != null && repairList.size() > 0) {
                                    List<Repair> repairMod = repairModel.getDataByRepairIdDistince();
                                    for (Repair repair: repairMod){
                                        repairMap.put(repair.getId_(), repair);
                                    }
                                    for (Repair repair : repairList) {
                                        if (!repairMap.containsKey(repair.getId_())){
                                            repairMap.put(repair.getId_(),repair);
                                            DaoManager.getDaoSession(MyApplication.APP_CONTEXT).getRepairDao().insertOrReplace(repair);
                                            // 获取详情
                                            if (repair.getDetailList() != null && repair.getDetailList().size() > 0) {
                                                for (RepailDetail repailDetail : repair.getDetailList()) {
                                                    repailDetail.setRepairId_(repair.getId_());

                                                    DaoManager.getDaoSession(MyApplication.APP_CONTEXT).getRepailDetailDao().insertOrReplace(repailDetail);
                                                }


                                            }
                                        }


                                    }
                                    getActivity().runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            refresh_list_repair.setRefreshing(false);
                                            ToastUtil.toastShort("下载维修单成功");
                                        }
                                    });
                                    refreshView();
                                }
                            }
                        }
                    } else {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                refresh_list_repair.setRefreshing(false);
                                ToastUtil.toastShort(MyApplication.APP_CONTEXT.getString(R.string.get_no_data));
                            }
                        });

                    }
                } else {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            repairView.hideProgressDialog();
                            ToastUtil.toastShort(response.message());
                        }
                    });

                }
            } else {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        refresh_list_repair.setRefreshing(false);
                        ToastUtil.toastShort(MyApplication.APP_CONTEXT.getString(R.string.get_data_fail));
                    }
                });

            }
        } catch (Exception e) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    refresh_list_repair.setRefreshing(false);
                }
            });

            e.printStackTrace();
        }
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                refresh_list_repair.setRefreshing(false);
            }
        });

    }

    private void refreshView() {
        repairPresenter.initRepairListData();
    }




}
